package com.liz.lizrpccore.beans.proxys.entrance;

import com.liz.lizrpccore.core.consts.GlobalConst;
import com.liz.lizrpccore.utils.SpringContextUtils;
import com.liz.lizrpccore.beans.proxys.base.LizAbstractProxy;
import com.liz.lizrpccore.enums.ProxyTypeEnum;
import com.liz.lizrpccore.properties.LizRpcProperties;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author liangGongWei
 * @description
 * @create 2021-08-25 14:55
 **/
@Slf4j
public class ServiceProxy<T>  implements InvocationHandler  {
    protected final Class<T> interfaceType;


    public ServiceProxy(Class<T> interfaceType) {
        this.interfaceType = interfaceType;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        log.info("调用前，参数：{}",Arrays.toString(args));
        //这里可以得到参数数组和方法等，可以通过反射，注解等，进行结果集的处理
        //mybatis就是在这里获取参数和相关注解，然后根据返回值类型，进行结果集的转换

        //这里通过自己的手段，获得远程调用的结果。
        Object res = this.getResultFromRemote(interfaceType,method,args);
        log.info("调用后，结果：{}", res);
        return res;
    }

    @SuppressWarnings("ALL")
    private Object getResultFromRemote(Class<T> interfaceType, Method method, Object[] args) {
        String proxyType = GlobalConst.getProxyType();
        LizAbstractProxy lizAbstractProxy = ProxyTypeEnum.getProxy(proxyType);
        return lizAbstractProxy.getResult(interfaceType,method,args);
    }
}
